<?php

class DCfSongs extends DActiveRecord {
    
    private $curPage = 0;
    private $defaultSort;
    public $params;
    public $musicFile;
    public $counter_start, $counter_end;

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }
    
    public function init() {
        parent::init();
        
        //set params
        $this->params['upload_dir'] = Yii::app()->params['upload_dir'] . 'music/';
        $this->params['upload_url'] = Yii::app()->params['document_root'] 
                . Yii::app()->params['upload_url'] . 'music/';
    }

    public function tableName() {
        return 'cf_songs';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        return array(
            array('album_id, composer_id, name, artist', 'required'),
            array('name, artist', 'length', 'max' => 255),
            array('counter', 'numerical', 'integerOnly' => true),
            array('musicFile', 'validateFile'),
            array('counter, sort_order, file, lyric', 'safe'),
            array('album_id, composer_id, name, artist, counter', 'safe', 'on' => 'search'),
        );
    }

    public function relations() {
        return array(
            'ralbum' => array(self::BELONGS_TO, 'DCfAlbum', 'album_id'),
            'rcomposer' => array(self::BELONGS_TO, 'DCfComposer', 'composer_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id'             => 'ID',
            'album_id'       => 'Album',
            'composer_id'    => 'Nhạc sĩ',
            'name'           => 'Tên bài hát',
            'artist'         => 'Ca sĩ',
            'musicFile'      => 'File (*.mp3)',
            'counter'        => 'Lượt nghe',
            'sort_order'     => 'Sắp xếp',
            'activated_flag' => 'Hiện',
            'lyric' => 'Lời bài hát',
            'category' => 'Phân loại',
        );
    }
    
    public function search() {
        //Restore state from session
        $this->restoreState();

        //Criteria
        $criteria = new CDbCriteria;
        $this->setTableAlias('t');
        $criteria->with = array('ralbum', 'rcomposer');
        $criteria->addCondition(('t.album_id = ralbum.id'));
        $criteria->compare('t.name', $this->name, true);
        $criteria->compare('t.activated_flag', $this->activated_flag);
        $criteria->compare('t.composer_id', $this->composer_id);
        $criteria->compare('t.album_id', $this->album_id);
        $criteria->compare('t.artist', $this->artist, true);
        $criteria->compare('t.counter', '>=' . $this->counter_start);
        $criteria->compare('t.counter', '<=' . $this->counter_end);

        //Sorting
        $sort               = new CSort();
        $sort->defaultOrder = ($this->defaultSort == '') ? array('sort_order' => true) : $this->defaultSort;
        $sort->attributes = array(
            'id' => array(
                'asc'      => 't.id ASC',
                'desc'     => 't.id DESC',
                'default'  => 'asc',
            ),
            'name' => array(
                'asc'      => 't.name ASC, t.sort_order DESC',
                'desc'     => 't.name DESC, t.sort_order DESC',
                'default'  => 'asc',
            ),
            'artist' => array(
                'asc'      => 't.artist ASC, t.sort_order DESC',
                'desc'     => 't.artist DESC, t.sort_order DESC',
                'default'  => 'asc',
            ),
            'counter' => array(
                'asc'      => 't.counter ASC, t.sort_order DESC',
                'desc'     => 't.counter DESC, t.sort_order DESC',
                'default'  => 'asc',
            ),
            'album_id' => array(
                'asc'      => 'ralbum.name ASC, t.sort_order DESC',
                'desc'     => 'ralbum.name DESC, t.sort_order DESC',
                'default'  => 'asc',
            ),
            'composer_id' => array(
                'asc'      => 'rcomposer.name ASC, t.sort_order DESC',
                'desc'     => 'rcomposer.name DESC, t.sort_order DESC',
                'default'  => 'asc',
            ),
            'activated_flag' => array(
                'asc'        => 't.activated_flag ASC',
                'desc'       => 't.activated_flag DESC',
                'default'    => 'asc',
            ),
            'sort_order' => array(
                'asc'      => 't.sort_order ASC',
                'desc'     => 't.sort_order DESC',
                'default'  => 'desc',
            ),
        );
        $sort->applyOrder($criteria);

        return new CActiveDataProvider($this, array(
            'criteria'   => $criteria,
            'sort'       => $sort,
            'pagination' => array('currentPage' => $this->curPage),
        ));
    }
    
    private function restoreState() {
        $state = SpsState::getState();

        if ($state) {
            if (isset($state['sort']))
                $this->defaultSort = $state['sort'];
            if (isset($state['page']))
                $this->curPage     = $state['page'];

            if (isset($state['search'])) {
                foreach ($state['search'] as $key => $value)
                    if ($value != '')
                        $this->$key = $value;
            }
        }
    }
    
    protected function beforeSave() {
        parent::beforeSave();
        
        //sort_order
        if ($this->getIsNewRecord()) {
            $this->setAttribute('sort_order', $this->getAutoIncrement($this->tableName()));
        }

        //title_seo
        $titleSeo = MyHelpers::getInstance()->convertSeoStr($this->name);
        $this->setAttribute('title_seo', $titleSeo);

        return true;
    }
    
    public function validateFile($attribute, $params) {
        $file = CUploadedFile::getInstance($this, $attribute);
        
        if ( ! $this->hasErrors() ) {
            if ( $file ) { //file is uploaded
                $success = true;
                $msg = '';
                $validFormat = array('mp3');

                //check format
                if ( ! in_array($file->getExtensionName(), $validFormat)) {
                    $msg = Yii::t('DadminModule.message', 'music_format_require');
                    $success = false;
                }

                if ( $success ) {
                    if ( $this->isNewRecord ) {
                        $fileName = $this->getAutoIncrement($this->tableName()) . '.' . $file->getExtensionName();
                    } else {
                        $fileName = $this->id . '.' . $file->getExtensionName();
                    }
                    $filePath = $this->params['upload_dir'] . $fileName;
                    $this->setAttribute('file', $fileName);
                    $file->saveAs($filePath);
                } else {
                    $this->addError($attribute, $msg);
                }
            } else {
                if ( $this->getIsNewRecord() ) {
                    $this->addError($attribute, Yii::t('DadminModule.message', 'required_file', array(
                        '{0}' => $this->getAttributeLabel($attribute),
                    )));
                }
            }
        }
        
        return TRUE;
    }
    
    protected function beforeDelete() {
        parent::beforeDelete();
        $this->deleteFile($this->file);
        return true;
    }

    private function deleteFile($fileName) {
        $path = $this->params['upload_dir'] . $fileName;
        return (is_file($path)) ? unlink($path) : FALSE;
    }
    
    /**
     * ========================== SORT HELPER ==========================
     */
    /**
     * Hoán đổi thuộc tính sort_order của 2 record có ID tương ứng
     * @param integer $pk1
     * @param integer $pk2 
     */
    public function swapSortOrder($pk1, $pk2) {
        $record_1    = $this->findByPk($pk1);
        $sortOrder_1 = $record_1->getAttribute('sort_order');

        $record_2    = $this->findByPk($pk2);
        $sortOrder_2 = $record_2->getAttribute('sort_order');

        //update
        $record_1->sort_order = $sortOrder_2;
        $record_1->save();

        $record_2->sort_order = $sortOrder_1;
        $record_2->save();
    }

    /**
     * Lấy Record của trang liền sau
     * @param CDBCriteria $criteria
     * @param integer $pageSize
     * @param integer $curPage
     * @return integer 
     */
    public function sortGetLesser($criteria, $pageSize, $curPage) {
        $command = Yii::app()->db->createCommand();
        $this->sortFillCommand($criteria, $command);

        //offset & limit
        $offset = ($curPage + 1) * $pageSize;
        $command->limit(1, $offset);
        $row    = $command->queryScalar($criteria->params);

        return $row;
    }

    /**
     * Lấy Record của trang liền trước
     * @param CDBCriteria $criteria
     * @param integer $pageSize
     * @param integer $curPage
     * @return integer 
     */
    public function sortGetGreater($criteria, $pageSize, $curPage) {
        $command = Yii::app()->db->createCommand();
        $this->sortFillCommand($criteria, $command);

        //offset & limit
        $offset = ($curPage - 1) * $pageSize + ($pageSize - 1);
        $command->limit(1, $offset);

        $row = $command->queryRow(true, $criteria->params);

        return $row['id'];
    }

    /**
     * Đưa record có $pk1 lên đầu (trong trang hiện hành)
     * @param integer $pk1
     * @param integer $pk2
     */
    public function sortMakeTop($pk1, $pk2) {
        //get records
        $record1 = $this->findByPk($pk1);
        $record2 = $this->findByPk($pk2);

        //Criteria
        $criteria = new CDbCriteria(array(
                'order' => 'sort_order ASC'
            ));
        $criteria->compare('sort_order', '>=' . $record1->sort_order);
        $criteria->compare('sort_order', '<=' . $record2->sort_order);

        $resultDB     = $this->findAll($criteria);
        $updatedValue = $record2->sort_order;

        foreach ($resultDB as $row) {
            $temp = $row->sort_order;

            $row->sort_order = $updatedValue;
            $row->save();

            $updatedValue = $temp;
        }

        return TRUE;
    }

    /**
     * Đưa record có $pk1 xuống dưới cùng (trong trang hiện hành)
     * @param integer $pk1
     * @param integer $pk2
     */
    public function sortMakeBottom($pk1, $pk2) {
        //get records
        $record1 = $this->findByPk($pk1);
        $record2 = $this->findByPk($pk2);

        //Criteria
        $criteria = new CDbCriteria(array(
                'order' => 'sort_order DESC'
            ));
        $criteria->compare('sort_order', '<=' . $record1->sort_order);
        $criteria->compare('sort_order', '>=' . $record2->sort_order);

        $resultDB     = $this->findAll($criteria);
        $updatedValue = $record2->sort_order;

        foreach ($resultDB as $row) {
            $temp = $row->sort_order;

            $row->sort_order = $updatedValue;
            $row->save();

            $updatedValue = $temp;
        }

        return TRUE;
    }

    /**
     * Get data from $criteria into $command
     * @param type $criteria
     * @param type $command 
     */
    private function sortFillCommand($criteria, $command) {
        $command->select('id')->from('cf_songs');

        if ($criteria->condition != '')
            $command->where($criteria->condition);
        if ($criteria->order != '')
            $command->order($criteria->order);
    }
    /**
     * ========================== //SORT HELPER ==========================
     */
}